import { combineReducers } from "redux";
import { Chat, Message } from "../creators/chat";
import { Account, Server } from "../creators/account";

function onlyUnique(value, index, self) {
  return self.indexOf(value) === index;
}

const initialState = {};

function chatsReducer(state = initialState, action) {
  switch (action.type) {
    case "ADD_CHAT":
      const newChat = new Chat(action.chatKey, action.chatKeyHash);
      return { ...state, [action.chatKeyHash]: { ...newChat } };

    case "NEW_MESSAGE":
      const newMessage = new Message(
        action.userName,
        "tst",
        action.timestamp,
        action.image,
        action.message
      );
      state[action.chatHash].messages.push(newMessage);
      return { ...state };

    case "ONLINE_LIST":
      if (typeof state[action.chatID].onlineList != "undefined") {
        state[action.chatID].onlineList = action.list.filter(onlyUnique).sort();
      } else {
        console.log(typeof state[action.chatID].onlineList);
      }
      return { ...state };
    default:
      return state;
  }
}

function accountReducer(state = initialState, action) {
  switch (action.type) {
    case "SET_ACCOUNT":
      const account = new Account(action.name);
      return { ...state, account };

    case "SET_SERVER":
      const server = new Server(action.srvaddr);
      return { ...state, server };

    default:
      return state;
  }
}

const rootReducer = combineReducers({
  chats: chatsReducer,
  account: accountReducer,
});

export default rootReducer;
